
import { _decorator, Component, director, JsonAsset, Label, Prefab, resources, Sprite, sys } from 'cc';
import { WECHAT } from 'cc/env';
import { Adsdk } from './Adsdk';
import { UILayerMgr } from './startScene/UILayerMgr';
import { StartSceneGameMgr } from './startScene/StartSceneGameMgr';
import { UserInfo } from './startScene/UserInfo';
import { Role } from './startScene/Role';
import { Equip } from './startScene/Equip';
import { roleEquipEnum } from './Enum';
import { Dictionary } from './utils/Dictionary';
import { StorageMgr } from './StorageMgr';
import { Pet } from './startScene/Pet';
import { PoolMgr } from './PoolMgr';
import { gameMgr } from './mainScene/gameMgr';
const { ccclass, property } = _decorator;
 
@ccclass('loading')
export class loading extends Component {

    @property(JsonAsset)
    roleCongfi: JsonAsset;
    @property(JsonAsset)
    equipCongfi: JsonAsset;
    @property(JsonAsset)
    rewardCongfi: JsonAsset;
    @property(JsonAsset)
    enemyCongfi: JsonAsset;
    @property(JsonAsset)
    petCongfi: JsonAsset;
    @property(JsonAsset)
    everyDayTaskCongfi: JsonAsset;
    @property(Sprite)
    load: Sprite = null;
    @property(Prefab)
    enemyPre: Prefab;
    @property(Prefab)
    minTipPre:Prefab;
  
    @property(Label)
    loadtxt: Label = null

    static ins: loading;

    load_num = 0;

    httpreq = false


    // roleCongfiDic: Dictionary<number, any> = new Dictionary();
    // equipCongfiDic: Dictionary<number, any> = new Dictionary();
    
    onLoad() {
  
        loading.ins=this;
        console.log('version:',StorageMgr.ins.VERSION,StorageMgr.ins.getStorage('userInfo'))
        
        //获取配置
        this.roleCongfi.json.forEach(element => {
            UserInfo.roleCongfiDic.set(element.roleType, element);
        });
        this.equipCongfi.json.forEach(element => {
            UserInfo.equipCongfiDic.set(element.equipType, element);
        });
        this.everyDayTaskCongfi.json.forEach(element => {
            UserInfo.everyDayTaskCongfiDic.set(element.everyTaskId, element);
        });
        this.rewardCongfi.json.forEach(element => {
            UserInfo.rewardCongfiDic.set(element.rewardType, element);
        });
        this.enemyCongfi.json.forEach(element => {
            UserInfo.enemyCongfiDic.set(element.enemyType, element);
        });
        this.petCongfi.json.forEach(element => {
            UserInfo.petCongfiDic.set(element.petType, element);
        });



        //获取缓存
        if (StorageMgr.ins.getStorage('userInfo')) {
            let userinfo = StorageMgr.ins.getStorage('userInfo');
            let roleinfo = StorageMgr.ins.getStorage('roleData');
            let equipinfo = StorageMgr.ins.getStorage('equipData');
            let petinfo = StorageMgr.ins.getStorage('petData');
            let petChipinfo = StorageMgr.ins.getStorage('petChipData');
            let roleChipinfo = StorageMgr.ins.getStorage('roleChipData');
            let _equipId = StorageMgr.ins.getStorage('equipId');
            let _petId = StorageMgr.ins.getStorage('petId');
            let _roleId = StorageMgr.ins.getStorage('roleId');
            StartSceneGameMgr.ins.EquipId = _equipId||0;
            StartSceneGameMgr.ins.PetId = _petId||0;
            StartSceneGameMgr.ins.RoleId = _roleId||0;
            UserInfo.level = userinfo.level||1;
            UserInfo.crystalMun = userinfo.crystalMun||UserInfo.crystalMun;
            UserInfo.coinMun=userinfo.coinMun||UserInfo.coinMun;
            UserInfo.epicBoxKeyNum = userinfo.epicBoxKeyNum || UserInfo.epicBoxKeyNum;
            UserInfo.legendBoxKeyNum = userinfo.legendBoxKeyNum || UserInfo.legendBoxKeyNum;
            UserInfo.signContinuousDayNum = userinfo.signContinuousDayNum || UserInfo.signContinuousDayNum;
            UserInfo.hasEndSkillPropArr = userinfo.hasEndSkillPropArr || UserInfo.hasEndSkillPropArr;
            UserInfo.receiveAchievementArr = userinfo.receiveAchievementArr || UserInfo.receiveAchievementArr;
            UserInfo.accumulateEvolvePlayerSkillFireBall = userinfo.accumulateEvolvePlayerSkillFireBall || UserInfo.accumulateEvolvePlayerSkillFireBall;
            UserInfo.accumulateEvolvePlayerSkillSpike = userinfo.accumulateEvolvePlayerSkillSpike || UserInfo.accumulateEvolvePlayerSkillSpike;
            UserInfo.accumulateEvolvePlayerSkillStarLightBullet = userinfo.accumulateEvolvePlayerSkillStarLightBullet || UserInfo.accumulateEvolvePlayerSkillStarLightBullet;
            UserInfo.accumulateHasRoleNum = userinfo.accumulateHasRoleNum || UserInfo.accumulateHasRoleNum

            UserInfo.isNewUser = false;
            UserInfo.currGoBattleRoleId = userinfo.currGoBattleRoleId || UserInfo.currGoBattleRoleId;
            StartSceneGameMgr.ins.roleSelectId = UserInfo.currGoBattleRoleId;
            UserInfo.seeAdvGetCrystalUseNum = parseInt(userinfo.seeAdvGetCrystalUseNum) || UserInfo.seeAdvGetCrystalUseNum;
            UserInfo.seeAdvGetCoinUseNum=parseInt(userinfo.seeAdvGetCoinUseNum)||UserInfo.seeAdvGetCoinUseNum;
            UserInfo.todayAlreadyIsSign = userinfo.todayAlreadyIsSign || UserInfo.todayAlreadyIsSign;
            UserInfo.openFreeBoxNum = parseInt(userinfo.openFreeBoxNum) || UserInfo.openFreeBoxNum;
            UserInfo.drawTurnTableNum = parseInt(userinfo.drawTurnTableNum) || UserInfo.drawTurnTableNum;
            UserInfo.todayEnhanceEquipNum = parseInt(userinfo.todayEnhanceEquipNum) || UserInfo.todayEnhanceEquipNum;
            UserInfo.todayBeatEnemyNum = parseInt(userinfo.todayBeatEnemyNum) || UserInfo.todayBeatEnemyNum;
            UserInfo.todayOpenBoxNum = parseInt(userinfo.todayOpenBoxNum) || UserInfo.todayOpenBoxNum;
            UserInfo.todayWinGateNum = parseInt(userinfo.todayWinGateNum) || UserInfo.todayWinGateNum;
            UserInfo.todayEveryDayTask = userinfo.todayEveryDayTask || UserInfo.todayEveryDayTask;

            if (roleinfo) {
                roleinfo.forEach(element => {
                    let roleClass: Role = new Role();
                    roleClass.initData(element)
                    UserInfo.hasRoleDic.set(element.roleId, roleClass)
                });
            }
            else {//避免版本更新报错
                StartSceneGameMgr.ins.getRole(1);
            }
            if (equipinfo) {
                equipinfo.forEach(element => {
                    let equipClass: Equip = new Equip();
                    equipClass.initData(element)
                    UserInfo.hasEquipDic.set(element.equipId, equipClass)
                });
            }
            else{//避免版本更新报错
                StartSceneGameMgr.ins.getEquip(0);
                StartSceneGameMgr.ins.getEquip(1);
                StartSceneGameMgr.ins.getEquip(2);
            }
            if (petinfo) {
                petinfo.forEach(element => {
                    let petClass: Pet = new Pet();
                    petClass.initData(element)
                    UserInfo.hasPetDic.set(element.petId, petClass)
                });
            }
            else {//避免版本更新报错
                StartSceneGameMgr.ins.getPet(0);
            }
            if (petChipinfo) {
                UserInfo.hasPetChipArr = petChipinfo;
            }
            else {//避免版本更新报错
                UserInfo.petCongfiDic.getValueList().forEach((ele) => {
                    UserInfo.hasPetChipArr[ele.petType] = 0;
                })
            }
            if (roleChipinfo) {
                UserInfo.hasRoleChipArr = roleChipinfo;
            }
            else {//避免版本更新报错
                UserInfo.roleCongfiDic.getValueList().forEach((ele) => {
                    UserInfo.hasRoleChipArr[ele.roleType] = 0;
                })
            }

            const now = new Date();
            const nowDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());

            if (StorageMgr.ins.getStorage('loginTodayTime') != nowDate.toLocaleString()) {//如果不是今天,重置今天数据
                StorageMgr.ins.setStorage('loginTodayTime',nowDate.toLocaleString())
                UserInfo.seeAdvGetCrystalUseNum = 0;
                UserInfo.seeAdvGetCoinUseNum = 0;
                UserInfo.todayAlreadyIsSign=false;
                UserInfo.openFreeBoxNum = 0;
                UserInfo.drawTurnTableNum=-1;
                UserInfo.todayEnhanceEquipNum=0;
                UserInfo.todayOpenBoxNum=0;
                UserInfo.todayBeatEnemyNum=0
                UserInfo.todayWinGateNum=0;
                UserInfo.todayEveryDayTask=null;
                StartSceneGameMgr.ins.saveGameDate();

                
                //签到
                if (UserInfo.signContinuousDayNum==6) {//如果已经连续签到7天
                    console.log("已经连续七天签到")
                    UserInfo.signContinuousDayNum=-1;
                    StartSceneGameMgr.ins.saveGameDate();
                }
            }
        

            //签到数据
            let newUserinfo = StorageMgr.ins.getStorage('userInfo');
            let loignData = new Date(StorageMgr.ins.getStorage('loginTodayTime'));

            if (loignData.getDate() == nowDate.getDate() || loignData.getDate() + 1 == nowDate.getDate()) {//如果今天等于今天，或者相隔一天
                UserInfo.signContinuousDayNum=parseInt(newUserinfo.signContinuousDayNum);
            }

            if (loignData.getFullYear()!=nowDate.getFullYear()||loignData.getMonth()!=nowDate.getMonth()) {
                console.log("每月，每年不相等")
                UserInfo.signContinuousDayNum=-1;
                StartSceneGameMgr.ins.saveGameDate();
            }


        }
        else {
            localStorage.clear();
            StartSceneGameMgr.ins.roleSelectId = UserInfo.currGoBattleRoleId;
            UserInfo.isNewUser=true

            StartSceneGameMgr.ins.getRole(1);
            // StartSceneGameMgr.ins.getRole(2);
            // StartSceneGameMgr.ins.getRole(5);
  
            StartSceneGameMgr.ins.getEquip(0);
            StartSceneGameMgr.ins.getEquip(1);
            StartSceneGameMgr.ins.getEquip(2);

            StartSceneGameMgr.ins.getPet(0);

            UserInfo.petCongfiDic.getValueList().forEach((ele)=>{
                UserInfo.hasPetChipArr[ele.petType]=0;
            })
            UserInfo.roleCongfiDic.getValueList().forEach((ele) => {
                UserInfo.hasRoleChipArr[ele.roleType] = 0;
            })

            //记录一下登录时间
            const now = new Date();
            const date = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            StorageMgr.ins.setStorage('loginTodayTime',date.toLocaleString());

            StartSceneGameMgr.ins.saveGameDate();

        }

        //加载池
        this.loadPool();

        //预创建需要用到的layer
        UILayerMgr.getIns.initLayerPrePool();

        this.loadtxt.string = '加载中...' + this.load_num * 100 + '%';
        this.load_num = 0
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            Adsdk.instance.getWxIdFromServer(() => {
                Adsdk.instance.init()
                this.httpreq = true
            }, () => {
                this.httpreq = true
            })
        } else if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            Adsdk.instance.init()
            this.httpreq = true
        } else {
            this.httpreq = true
        }

                
    }

    async loadPool() {
        await new Promise((resolve, reject) => {
            resources.loadDir("prefabs/ele/playerSkill", Prefab, (err, res) => {
                for (let i = 0; i < res.length; i++) {
                    StartSceneGameMgr.ins.skillPrefabDic.set(res[i].name, res[i])
                    if (i + 1 == res.length) {
                        resolve(true)
                    }
                }

            })

        })
        console.log(StartSceneGameMgr.ins.skillPrefabDic, "this.skillPrefabDic")


        await PoolMgr.getIns().initAllPool("enemy", this.enemyPre, 100);
        await PoolMgr.getIns().initAllPool("minTip", this.minTipPre, 80);
        await PoolMgr.getIns().initAllPool("arrowHuolongguo", StartSceneGameMgr.ins.skillPrefabDic.get("arrowHuolongguo"), 20);
        await PoolMgr.getIns().initAllPool("arrowLajiao", StartSceneGameMgr.ins.skillPrefabDic.get("arrowLajiao"), 20);
        await PoolMgr.getIns().initAllPool("arrowLanmei", StartSceneGameMgr.ins.skillPrefabDic.get("arrowLanmei"), 20);
        await PoolMgr.getIns().initAllPool("arrowSuantou", StartSceneGameMgr.ins.skillPrefabDic.get("arrowSuantou"), 20);
        await PoolMgr.getIns().initAllPool("fireBall", StartSceneGameMgr.ins.skillPrefabDic.get("fireBall"), 4);
        await PoolMgr.getIns().initAllPool("Light", StartSceneGameMgr.ins.skillPrefabDic.get("Light"), 4);
        await PoolMgr.getIns().initAllPool("moonSlash", StartSceneGameMgr.ins.skillPrefabDic.get("moonSlash"), 4);
        await PoolMgr.getIns().initAllPool("spike", StartSceneGameMgr.ins.skillPrefabDic.get("spike"), 4);
        await PoolMgr.getIns().initAllPool("spinArrow", StartSceneGameMgr.ins.skillPrefabDic.get("spinArrow"), 4);
        await PoolMgr.getIns().initAllPool("starlightBullet", StartSceneGameMgr.ins.skillPrefabDic.get("starlightBullet"), 4);
    }


    update(dt) {
        if (UILayerMgr.getIns.isInitAlready==false) {
            if (this.load_num>0.9) {
                return;
            }
        }

        this.load_num += dt
        this.loadtxt.string = '加载中...'+((this.load_num)*100).toFixed(2)+'%';
        this.load.fillRange = this.load_num;
        if(this.load.fillRange>=0.99&&this.httpreq&&UILayerMgr.getIns.isInitAlready){
            console.log("加载完成")
            this.loadtxt.string = '加载中...100%';
            if (UserInfo.isNewUser) {
                // director.loadScene('main')
                director.loadScene('start')
            }
            else {
                director.loadScene('start')
            }
        }
    }

}

